/**
 * 
 */
package guice.trail.lessons.scopes;

import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scope;

/**
 * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
 * 
 */
public class ThreadLocalScope implements Scope {

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.google.inject.Scope#scope(com.google.inject.Key,
	 *      com.google.inject.Provider)
	 */
	@Override
	public <T> Provider<T> scope(Key<T> key, final Provider<T> unscoped) {
		System.out.println("Scoping " + key.toString());
		return new Provider<T>() {
			private final ThreadLocal<T> threadData = new ThreadLocal<T>();

			public T get() {
				T instance = threadData.get();
				if (instance == null) {
					instance = unscoped.get();
					threadData.set(instance);
				}
				System.out.printf("I am threadlocal %s with hashcode: %s\n", instance.getClass().getSimpleName(),
						instance.hashCode());
				return instance;
			}
		};
	}

}
